<?php

namespace app\admin\controller\user;

use app\common\controller\Backend;
use app\common\library\Auth;
use think\Db;
use app\common\model\UserBeansLog;

/**
 * 会员管理
 *
 * @icon fa fa-user
 */
class User extends Backend
{

    protected $relationSearch = true;
    protected $searchFields = 'id,username,nickname';

    /**
     * @var \app\admin\model\User
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('User');
        $this->db2 = Db::connect(config('database.db2'));
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $where2 = '1=1 ';
            // $where2 = 'status!="cancel" ';
            $filter = $this->request->get("filter", '');
            $filter = (array)json_decode($filter, true);
            if (isset($filter['status'])) {
                if ($filter['status']=='正常') {
                    $where2 = 'user.status="normal" and user.is_limited=0';
                } elseif($filter['status']=='已限制') {
                    $where2 = 'user.status="normal" and user.is_limited=1';
                } elseif($filter['status']=='已拉黑') {
                    $where2 = 'user.status="hidden"';
                } elseif($filter['status']=='注销') {
                    $where2 = 'user.status="cancel"';
                }
            } 
            if (isset($filter['username'])) {
                $user_withdrawal_log = $this->db2->name('user_withdrawal_log')->where('real_name like"%'.$filter['username'].'%"')->group('user_id')->select();
                $user_ids = '';
                foreach ($user_withdrawal_log as $key => $value) {
                    $user_ids .= $value['user_id'].',';
                }
                $user_ids = trim($user_ids,',');
                $where2 .= ' and user.id in ('.$user_ids.')';
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->db2->name('user')->alias('user')
                ->where($where)
                ->where($where2)
                ->where('user.user_type',2)
                ->order($sort, $order)
                ->paginate($limit);
            $list2 = $list->items();
            foreach ($list2 as $k => &$v) {
                $v['avatar'] = $v['avatar'] ? cdnurl($v['avatar'], true) : letter_avatar($v['nickname']);
                // $v->hidden(['password']);
                // 上级
                $v['pid'] = $this->db2->name('user')->where('id',$v['pid'])->value('nickname');
                // 不满意反馈次数
                $v['bio'] = $this->db2->name('play_order')->where(['order_status'=>['in',[-5,-6]],'user_id'=>$v['id']])->count();
                // 完成订单次数
                $v['gender'] = order_count_read($v['id']);
                // 团队人数
                $v['birthday'] = $this->db2->name('user')->where(['pid'=>$v['id']])->count();
                // 累积返现
                $v['token'] = $this->db2->name('user_beans_log')->where(['log_type'=>['in','1,3,5,6'],'user_id'=>$v['id']])->value('sum(beans)');
                // 首次下单定位
                $visit = $this->db2->name('play_order')->field('location,create_dt')->where(['user_id'=>$v['id'],'order_status'=>3])->order('id DESC')->find();
                if (!$visit) {
                    $visit = $this->db2->name('mtofficial_order')->field('location,create_dt')->where(['user_id'=>$v['id'],'order_status'=>3])->order('id DESC')->find();
                }
                $v['email'] = '';
                if (isset($visit['location']) && $visit['location']) {
                    $v['email'] = $visit['location'];
                } elseif (isset($visit['area']) && $visit['area']) {
                    $v['email'] = $visit['area'];
                }
                // 用户状态
                if ($v['status']=='cancel') {
                    $v['status']='注销';
                } elseif ($v['status']=='hidden') {
                    $v['status']='已拉黑';
                } elseif ($v['is_limited']==1) {
                    $v['status']='已限制';
                } else {
                    $v['status'] = '正常';
                }
                // 拉黑原因
                $v['verification'] = $this->db2->name('blacklist_item')->where(['user_id'=>$v['id'],'status'=>1])->value('reason')??'';
                // 真实姓名
                $v['username'] = $this->db2->name('user_withdrawal_log')->where(['user_id'=>$v['id']])->order('id DESC')->value('real_name');
                $v['id'] = $v['id']+config('virtual_userid');
                // 最后一次下单
                $v['salt']=isset($visit['create_dt'])?$visit['create_dt']:'';
            }
            $result = array("total" => $list->total(), "rows" => $list2);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $this->token();
        }
        return parent::add();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $ids = $ids-config('virtual_userid');
        if ($this->request->isPost()) {
            $this->token();
        }
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $this->view->assign('groupList', build_select('row[group_id]', \app\admin\model\UserGroup::column('id,name'), $row['group_id'], ['class' => 'form-control selectpicker']));
        $level_order = 0;
        $users = Db::name('user')->where('pid',$ids)->field('id')->select();
        foreach ($users as $key => $value) {
            $level_order += order_count_read($value['id']);
        }
        $puser = Db::name('user')->where('id',$row['pid'])->value('id');
        if ($puser) {
            $puser = $puser+config('virtual_userid');
        } else {
            $puser = 0;
        }
        $this->view->assign('puser',$puser);
        $this->view->assign('level_order',$level_order);
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    // if ($this->modelValidate) {
                    //     $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    //     $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                    //     $row->validateFailException(true)->validate($validate);
                    // }
                    $update = [];
                    if (!$params['id']) {
                        $this->error('确少参数');
                    }
                    if (isset($params['pid'])) {
                        if ($params['pid']==$params['id']) $this->error('参数有误');
                        if ($params['pid']!=$row['pid']) {
                            $update['pid'] = $params['pid'];
                        }
                    }
                    if (isset($params['mobile']) && $params['mobile']) {
                        $mobile = Db::name('user')->where('id!='.$params['id'].' and user_type=2 and mobile="'.$params['mobile'].'" and status in ("normal","hidden")')->find();
                        if ($mobile) $this->error('手机号被占用');
                        if ($params['mobile']!=$row['mobile']) {
                            $update['mobile'] = $params['mobile'];
                        }
                    }
                    if (isset($params['level']) && $params['level']!=$row['level']) {
                        $update['level'] = $params['level'];
                    }
                    if ($params['status']=='normal' && $row['status']=='cancel') {
                        if (Db::name('user')->where('unionid="'.$row['unionid'].'" and user_type=2 and status in ("normal","hidden")')->count()) {
                            $this->error('用户已注册新账号');
                        }
                        $mobile = Db::name('user')->where('id!='.$params['id'].' and user_type=2 and mobile="'.$params['mobile'].'" and status in ("normal","hidden")')->find();
                        if ($mobile) $this->error('用户手机号被占用');
                        $update['status'] = "normal";
                    }
                    if ($params['status']=='cancel' && $row['status']=='normal') {
                        $update['status'] = "cancel";
                    }
                    $real_name = $this->db2->name('user_withdrawal_log')->where(['user_id'=>$row['id']])->order('id DESC')->field('id,real_name')->find();
                    if (isset($params['username']) && $real_name && $params['username']!=$real_name['real_name']) {
                        $update['username'] = $params['username'];
                        Db::name('user_withdrawal_log')->where(['id'=>$real_name['id']])->update(['real_name'=>$params['username']]);
                    }
                    if (!$update) $this->error('没有改动数据');
                    $update['id'] = $params['id'];
                    $result = $row->allowField(true)->save($update);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $row['username'] = $this->db2->name('user_withdrawal_log')->where(['user_id'=>$row['id']])->order('real_name DESC')->value('real_name');
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        $ids = $ids-config('virtual_userid');
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        Auth::instance()->delete($row['id']);
        $this->success();
    }

    /**
     * 修改吃豆
     * @DateTime 2023-05-26T17:02:07+0800
     * @param    [type]                   $ids [description]
     * @return   [type]                        [description]
     */
    public function beans($ids)
    {
        if (!$this->request->isAjax()) {
            $ids = $ids-config('virtual_userid');
        }
        $row = $this->model->get(['id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isAjax()) {
            $fields = ['beans' => 'beans'];
            $field = input('field', '');
            $value = input('val', 0);
            if (!in_array($field, array_keys($fields))) $this->error('不能修改');
            if ($value == 0) $this->error('变动不能为0');
            Db::startTrans();
            try {
                if ($field == 'beans') {
                    // $extend = [
                    //     'operation_name' => $this->auth->nickname,
                    // ];
                    // \app\common\model\User::beans($value, $ids, '管理员操作', 1, $extend);
                    $afterMoney = bcadd($row->beans, $value,2);
                    $extend = [
                        'before_beans' => $row->beans,
                        'after_beans' => $afterMoney,
                        'log_status' => 1,
                        'operation_name' => $this->auth->nickname,
                    ];
                    if ($value>0) {
                        UserBeansLog::addLog($row->id, 7, $value, '客服处理，异常补豆', $extend);
                    } else {
                        UserBeansLog::addLog($row->id, 7, $value, '售后处理，异常扣豆', $extend);
                    }
                    //变更余额
                    $row->beans = $afterMoney;
                    $row->save();
                    Db::commit();
                    $this->success('操作成功', null, $row->beans);
                }
                Db::rollback();
                $this->error('操作失败', null);
            } catch (Exception $e) {
                Db::rollback();
                $this->error('操作失败', null);
            }
        }
        $this->view->assign("row", $row->toArray());
        return $this->view->fetch();
    }   

    // 拉黑
    public function lh($ids = null)
    {
        $ids = $ids-config('virtual_userid');
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($row['status'] == 'hidden') {
            $this->error(__('请不要重复拉黑！'));
        }
        if ($this->request->isPost()) {
            $result = false;
            Db::startTrans();
            try {
                //是否采用模型验证
                if ($this->modelValidate) {
                    $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                    $row->validateFailException(true)->validate($validate);
                }
                $reason = input('reason', '','htmlentities');
                // 审核通过
                $result = $row->allowField(true)->save([
                    'status' => 'hidden',
                    'updatetime' => time(),
                ]);
                Db::name('blacklist_item')->insert([
                    'user_id'=>$ids,
                    'status'=>1,
                    'submit_by'=>$this->auth->id,
                    'mode'=>1,
                    'type'=>'管理员拉黑',
                    'reason'=>$reason
                ]);
                Db::commit();
            } catch (ValidateException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success();
            } else {
                $this->error(__('No rows were updated'));
            }
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }  

    // 限制
    public function xz($ids = null)
    {
        $ids = $ids-config('virtual_userid');
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($row['is_limited'] == 1) {
            $this->error(__('请不要重复限制！'));
        }
        if ($this->request->isPost()) {
            $result = false;
            Db::startTrans();
            try {
                //是否采用模型验证
                if ($this->modelValidate) {
                    $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                    $row->validateFailException(true)->validate($validate);
                }
                // 审核通过
                $result = $row->allowField(true)->save([
                    'is_limited' => 1,
                    'updatetime' => time(),
                ]);
                Db::name('blacklist_item')->insert([
                    'user_id'=>$ids,
                    'status'=>1,
                    'submit_by'=>$this->auth->id,
                    'mode'=>2
                ]);
                Db::commit();
            } catch (ValidateException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success();
            } else {
                $this->error(__('No rows were updated'));
            }
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    // 恢复禁用
    public function hfjy($ids = null)
    {
        $ids = $ids-config('virtual_userid');
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($row['status'] == 'normal') {
            $this->error(__('状态有误'));
        }
        if ($this->request->isPost()) {
            $result = false;
            Db::startTrans();
            try {
                //是否采用模型验证
                if ($this->modelValidate) {
                    $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                    $row->validateFailException(true)->validate($validate);
                }
                // 审核通过
                $result = $row->allowField(true)->save([
                    'status' => 'normal',
                    'updatetime' => time(),
                ]);
                Db::name('blacklist_item')->insert([
                    'user_id'=>$ids,
                    'status'=>1,
                    'submit_by'=>$this->auth->id,
                    'mode'=>3
                ]);
                Db::commit();
            } catch (ValidateException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success();
            } else {
                $this->error(__('No rows were updated'));
            }
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    // 恢复限制
    public function hfxz($ids = null)
    {
        $ids = $ids-config('virtual_userid');
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($row['is_limited'] == 0) {
            $this->error(__('状态有误'));
        }
        if ($this->request->isPost()) {
            $result = false;
            Db::startTrans();
            try {
                //是否采用模型验证
                if ($this->modelValidate) {
                    $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                    $row->validateFailException(true)->validate($validate);
                }
                // 审核通过
                $result = $row->allowField(true)->save([
                    'is_limited' => 0,
                    'updatetime' => time(),
                ]);
                Db::name('blacklist_item')->insert([
                    'user_id'=>$ids,
                    'status'=>1,
                    'submit_by'=>$this->auth->id,
                    'mode'=>4
                ]);
                Db::commit();
            } catch (ValidateException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success();
            } else {
                $this->error(__('No rows were updated'));
            }
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    public function item()
    {
        $ids = input('ids',0);
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $model = new \app\common\model\BlacklistItem();
            $list = $model
                ->where($where)
                ->where('chbc_blacklist_item.status',1)
                ->where('chbc_blacklist_item.user_id',$ids)
                ->with('user')
                ->order('id desc')
                ->paginate($limit);
            foreach ($list as $k => $v) {
                $v->getRelation('user')->visible(['nickname','mobile','equipment_code','joinip']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        $ids = $ids-config('virtual_userid');
        $this->view->assign("ids", $ids);
        return $this->view->fetch();
    }

    // 限制下单
    public function xzxd($ids = null)
    {
        $ids = $ids-config('virtual_userid');
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($row['xzxd'] == 1) {
            $this->error(__('已经是限制状态'));
        }
        if ($this->request->isPost()) {
            $result = false;
            Db::startTrans();
            try {
                //是否采用模型验证
                if ($this->modelValidate) {
                    $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                    $row->validateFailException(true)->validate($validate);
                }
                // 审核通过
                $result = $row->allowField(true)->save([
                    'xzxd' => 1,
                    'updatetime' => time(),
                ]);
                Db::commit();
            } catch (ValidateException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success();
            } else {
                $this->error(__('No rows were updated'));
            }
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }  

    // 允许下单
    public function yxxd($ids = null)
    {
        $ids = $ids-config('virtual_userid');
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($row['xzxd'] == 0) {
            $this->error(__('已经是允许下单状态'));
        }
        if ($this->request->isPost()) {
            $result = false;
            Db::startTrans();
            try {
                //是否采用模型验证
                if ($this->modelValidate) {
                    $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                    $row->validateFailException(true)->validate($validate);
                }
                // 审核通过
                $result = $row->allowField(true)->save([
                    'xzxd' => 0,
                    'updatetime' => time(),
                ]);
                Db::commit();
            } catch (ValidateException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success();
            } else {
                $this->error(__('No rows were updated'));
            }
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    } 

    // 会员团长
    public function hytz($ids = null)
    {
        $ids = $ids-config('virtual_userid');
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($row['hytz'] == 1) {
            $this->error(__('已经是会员团长'));
        }
        if ($this->request->isPost()) {
            $result = false;
            Db::startTrans();
            try {
                //是否采用模型验证
                if ($this->modelValidate) {
                    $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                    $row->validateFailException(true)->validate($validate);
                }
                // 审核通过
                $result = $row->allowField(true)->save([
                    'hytz' => 1,
                    'updatetime' => time(),
                ]);
                Db::commit();
            } catch (ValidateException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success();
            } else {
                $this->error(__('No rows were updated'));
            }
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    } 

    // 取消会员团长
    public function qxhytz($ids = null)
    {
        $ids = $ids-config('virtual_userid');
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($row['hytz'] == 0) {
            $this->error(__('该用户不是会员团长'));
        }
        if ($this->request->isPost()) {
            $result = false;
            Db::startTrans();
            try {
                //是否采用模型验证
                if ($this->modelValidate) {
                    $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                    $row->validateFailException(true)->validate($validate);
                }
                // 审核通过
                $result = $row->allowField(true)->save([
                    'hytz' => 0,
                    'updatetime' => time(),
                ]);
                Db::commit();
            } catch (ValidateException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success();
            } else {
                $this->error(__('No rows were updated'));
            }
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    } 

    /**
     * 生成查询所需要的条件,排序方式
     * @param mixed   $searchfields   快速查询的字段
     * @param boolean $relationSearch 是否关联查询
     * @return array
     */
    protected function buildparams($searchfields = null, $relationSearch = null)
    {
        $searchfields = is_null($searchfields) ? $this->searchFields : $searchfields;
        $relationSearch = is_null($relationSearch) ? $this->relationSearch : $relationSearch;
        $search = $this->request->get("search", '');
        $filter = $this->request->get("filter", '');
        $op = $this->request->get("op", '', 'trim');
        $sort = $this->request->get("sort", !empty($this->model) && $this->model->getPk() ? $this->model->getPk() : 'id');
        $order = $this->request->get("order", "DESC");
        $offset = $this->request->get("offset/d", 0);
        $limit = $this->request->get("limit/d", 999999);
        //新增自动计算页码
        $page = $limit ? intval($offset / $limit) + 1 : 1;
        if ($this->request->has("page")) {
            $page = $this->request->get("page/d", 1);
        }
        $this->request->get([config('paginate.var_page') => $page]);
        $filter = (array)json_decode($filter, true);
        // 状态参数过滤掉
        if (isset($filter['status'])) {
            unset($filter['status']);
        }
        if (isset($filter['username'])) {
            unset($filter['username']);
        }
        if (isset($filter['id'])) {
            $filter['id'] = $filter['id']-config('virtual_userid');
        }
        if (isset($filter['pid'])) {
            $filter['pid'] = $filter['pid']-config('virtual_userid');
        }
        $op = (array)json_decode($op, true);
        $filter = $filter ? $filter : [];
        $where = [];
        $alias = [];
        $bind = [];
        $name = '';
        $aliasName = '';
        if (!empty($this->model) && $this->relationSearch) {
            $name = $this->model->getTable();
            $alias[$name] = \think\Loader::parseName(basename(str_replace('\\', '/', get_class($this->model))));
            $aliasName = $alias[$name] . '.';
        }
        $sortArr = explode(',', $sort);
        foreach ($sortArr as $index => & $item) {
            $item = stripos($item, ".") === false ? $aliasName . trim($item) : $item;
        }
        unset($item);
        $sort = implode(',', $sortArr);
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $where[] = [$aliasName . $this->dataLimitField, 'in', $adminIds];
        }
        if ($search) {
            $searcharr = is_array($searchfields) ? $searchfields : explode(',', $searchfields);
            foreach ($searcharr as $k => &$v) {
                $v = stripos($v, ".") === false ? $aliasName . $v : $v;
            }
            unset($v);
            $where[] = [implode("|", $searcharr), "LIKE", "%{$search}%"];
        }
        $index = 0;
        foreach ($filter as $k => $v) {
            if (!preg_match('/^[a-zA-Z0-9_\-\.]+$/', $k)) {
                continue;
            }
            $sym = isset($op[$k]) ? $op[$k] : '=';
            if (stripos($k, ".") === false) {
                $k = $aliasName . $k;
            }
            $v = !is_array($v) ? trim($v) : $v;
            $sym = strtoupper(isset($op[$k]) ? $op[$k] : $sym);
            //null和空字符串特殊处理
            if (!is_array($v)) {
                if (in_array(strtoupper($v), ['NULL', 'NOT NULL'])) {
                    $sym = strtoupper($v);
                }
                if (in_array($v, ['""', "''"])) {
                    $v = '';
                    $sym = '=';
                }
            }

            switch ($sym) {
                case '=':
                case '<>':
                    $where[] = [$k, $sym, (string)$v];
                    break;
                case 'LIKE':
                case 'NOT LIKE':
                case 'LIKE %...%':
                case 'NOT LIKE %...%':
                    $where[] = [$k, trim(str_replace('%...%', '', $sym)), "%{$v}%"];
                    break;
                case '>':
                case '>=':
                case '<':
                case '<=':
                    $where[] = [$k, $sym, intval($v)];
                    break;
                case 'FINDIN':
                case 'FINDINSET':
                case 'FIND_IN_SET':
                    $v = is_array($v) ? $v : explode(',', str_replace(' ', ',', $v));
                    $findArr = array_values($v);
                    foreach ($findArr as $idx => $item) {
                        $bindName = "item_" . $index . "_" . $idx;
                        $bind[$bindName] = $item;
                        $where[] = "FIND_IN_SET(:{$bindName}, `" . str_replace('.', '`.`', $k) . "`)";
                    }
                    break;
                case 'IN':
                case 'IN(...)':
                case 'NOT IN':
                case 'NOT IN(...)':
                    $where[] = [$k, str_replace('(...)', '', $sym), is_array($v) ? $v : explode(',', $v)];
                    break;
                case 'BETWEEN':
                case 'NOT BETWEEN':
                    $arr = array_slice(explode(',', $v), 0, 2);
                    if (stripos($v, ',') === false || !array_filter($arr, function($v){
                        return $v != '' && $v !== false && $v !== null;
                    })) {
                        continue 2;
                    }
                    //当出现一边为空时改变操作符
                    if ($arr[0] === '') {
                        $sym = $sym == 'BETWEEN' ? '<=' : '>';
                        $arr = $arr[1];
                    } elseif ($arr[1] === '') {
                        $sym = $sym == 'BETWEEN' ? '>=' : '<';
                        $arr = $arr[0];
                    }
                    $where[] = [$k, $sym, $arr];
                    break;
                case 'RANGE':
                case 'NOT RANGE':
                    $v = str_replace(' - ', ',', $v);
                    $arr = array_slice(explode(',', $v), 0, 2);
                    if (stripos($v, ',') === false || !array_filter($arr)) {
                        continue 2;
                    }
                    //当出现一边为空时改变操作符
                    if ($arr[0] === '') {
                        $sym = $sym == 'RANGE' ? '<=' : '>';
                        $arr = $arr[1];
                    } elseif ($arr[1] === '') {
                        $sym = $sym == 'RANGE' ? '>=' : '<';
                        $arr = $arr[0];
                    }
                    $tableArr = explode('.', $k);
                    if (count($tableArr) > 1 && $tableArr[0] != $name && !in_array($tableArr[0], $alias) && !empty($this->model)) {
                        //修复关联模型下时间无法搜索的BUG
                        $relation = Loader::parseName($tableArr[0], 1, false);
                        $alias[$this->model->$relation()->getTable()] = $tableArr[0];
                    }
                    $where[] = [$k, str_replace('RANGE', 'BETWEEN', $sym) . ' TIME', $arr];
                    break;
                case 'NULL':
                case 'IS NULL':
                case 'NOT NULL':
                case 'IS NOT NULL':
                    $where[] = [$k, strtolower(str_replace('IS ', '', $sym))];
                    break;
                default:
                    break;
            }
            $index++;
        }
        if (!empty($this->model)) {
            $this->model->alias($alias);
        }
        $model = $this->model;
        $where = function ($query) use ($where, $alias, $bind, &$model) {
            if (!empty($model)) {
                $model->alias($alias);
                $model->bind($bind);
            }
            foreach ($where as $k => $v) {
                if (is_array($v)) {
                    call_user_func_array([$query, 'where'], $v);
                } else {
                    $query->where($v);
                }
            }
        };
        return [$where, $sort, $order, $offset, $limit, $page, $alias, $bind];
    }

    /**
     * Selectpage的实现方法
     *
     * 当前方法只是一个比较通用的搜索匹配,请按需重载此方法来编写自己的搜索逻辑,$where按自己的需求写即可
     * 这里示例了所有的参数，所以比较复杂，实现上自己实现只需简单的几行即可
     *
     */
    protected function selectpage()
    {
        //设置过滤方法
        $this->request->filter(['trim', 'strip_tags', 'htmlspecialchars']);

        //搜索关键词,客户端输入以空格分开,这里接收为数组
        $word = (array)$this->request->request("q_word/a");
        //当前页
        $page = $this->request->request("pageNumber");
        //分页大小
        $pagesize = $this->request->request("pageSize");
        //搜索条件
        $andor = $this->request->request("andOr", "and", "strtoupper");
        //排序方式
        $orderby = (array)$this->request->request("orderBy/a");
        //显示的字段
        $field = $this->request->request("showField");
        //主键
        $primarykey = $this->request->request("keyField");
        //主键值
        $primaryvalue = $this->request->request("keyValue");
        //搜索字段
        $searchfield = (array)$this->request->request("searchField/a");
        //自定义搜索条件
        $custom = (array)$this->request->request("custom/a");
        //是否返回树形结构
        $istree = $this->request->request("isTree", 0);
        $ishtml = $this->request->request("isHtml", 0);
        if ($istree) {
            $word = [];
            $pagesize = 999999;
        }
        $order = [];
        foreach ($orderby as $k => $v) {
            $order[$v[0]] = $v[1];
        }
        $field = $field ? $field : 'name';

        //如果有primaryvalue,说明当前是初始化传值
        if ($primaryvalue !== null) {
            $where = [$primarykey => ['in', $primaryvalue]];
            $pagesize = 999999;
        } else {
            $where = function ($query) use ($word, $andor, $field, $searchfield, $custom) {
                $logic = $andor == 'AND' ? '&' : '|';
                $searchfield = is_array($searchfield) ? implode($logic, $searchfield) : $searchfield;
                $searchfield = str_replace(',', $logic, $searchfield);
                $word = array_filter(array_unique($word));
                if (count($word) == 1) {
                    $query->where($searchfield, "like", "%" . reset($word) . "%");
                } else {
                    $query->where(function ($query) use ($word, $searchfield) {
                        foreach ($word as $index => $item) {
                            $query->whereOr(function ($query) use ($item, $searchfield) {
                                $query->where($searchfield, "like", "%{$item}%");
                            });
                        }
                    });
                }
                if ($custom && is_array($custom)) {
                    foreach ($custom as $k => $v) {
                        if (is_array($v) && 2 == count($v)) {
                            $query->where($k, trim($v[0]), $v[1]);
                        } else {
                            $query->where($k, '=', $v);
                        }
                    }
                }
            };
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = [];
        $total = $this->model->where($where)->count();
        if ($total > 0) {
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }

            $fields = is_array($this->selectpageFields) ? $this->selectpageFields : ($this->selectpageFields && $this->selectpageFields != '*' ? explode(',', $this->selectpageFields) : []);

            //如果有primaryvalue,说明当前是初始化传值,按照选择顺序排序
            if ($primaryvalue !== null && preg_match("/^[a-z0-9_\-]+$/i", $primarykey)) {
                $primaryvalue = array_unique(is_array($primaryvalue) ? $primaryvalue : explode(',', $primaryvalue));
                //修复自定义data-primary-key为字符串内容时，给排序字段添加上引号
                $primaryvalue = array_map(function ($value) {
                    return '\'' . $value . '\'';
                }, $primaryvalue);

                $primaryvalue = implode(',', $primaryvalue);

                $this->model->orderRaw("FIELD(`{$primarykey}`, {$primaryvalue})");
            } else {
                $this->model->order($order);
            }

            $datalist = $this->model->where($where)
                ->where('user_type',2)
                ->page($page, $pagesize)
                ->select();

            foreach ($datalist as $index => $item) {
                unset($item['password'], $item['salt']);
                if ($this->selectpageFields == '*') {
                    $result = [
                        $primarykey => isset($item[$primarykey]) ? $item[$primarykey] : '',
                        $field      => isset($item[$field]) ? $item[$field] : '',
                    ];
                } else {
                    $result = array_intersect_key(($item instanceof Model ? $item->toArray() : (array)$item), array_flip($fields));
                }
                $result['pid'] = isset($item['pid']) ? $item['pid'] : (isset($item['parent_id']) ? $item['parent_id'] : 0);
                $list[] = $result;
            }
            if ($istree && !$primaryvalue) {
                $tree = Tree::instance();
                $tree->init(collection($list)->toArray(), 'pid');
                $list = $tree->getTreeList($tree->getTreeArray(0), $field);
                if (!$ishtml) {
                    foreach ($list as &$item) {
                        $item = str_replace('&nbsp;', ' ', $item);
                    }
                    unset($item);
                }
            }
        }
        //这里一定要返回有list这个字段,total是可选的,如果total<=list的数量,则会隐藏分页按钮
        return json(['list' => $list, 'total' => $total]);
    }

    // 加优惠券
    public function roll($ids = null)
    {
        $ids = $ids-config('virtual_userid');
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $result = false;
            Db::startTrans();
            try {
                $params = $this->request->post("row/a");
                if (!$params['id'] || !$params['roll_type']) {
                    $this->error('缺少参数');
                }
                if (!in_array($params['roll_type'], ['card_one','card_two','card_three','card_four','card_five'])) {
                    $this->error('参数有误');
                }
                $roll_name = \think\Config::get('site.'.$params['roll_type']);
                $date = date('Y-m-d H:i:s');
                if ($params['roll_type']=='card_four') {
                    $expire_time = time()+259200;
                } else {
                    $expire_time = time()+2592000;
                }
                $data = [
                    'user_id'=>$ids,
                    'status'=>1,
                    'roll_type'=>$params['roll_type'],
                    'roll_name'=>$roll_name,
                    'create_dt'=>$date,
                    'update_dt'=>$date,
                    'expire_time'=>$expire_time,
                    'source'=>'系统发放',
                ];
                Db::name('user_roll')->insert($data);
                Db::commit();
            } catch (ValidateException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            $this->success();
        }
        // 优惠券
        $roll = Db::name('config')->where(['group'=>'cardroll','type'=>'string'])->select();
        $this->view->assign("row", $row);
        $this->view->assign("roll", $roll);
        return $this->view->fetch();
    }
}
